var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// var propsRouter = require('./routes/props');

const UserRouter = require('./routes/admin/UserRouter');
const NewsRouter = require('./routes/admin/NewsRouter');  //news
const PropRouter = require('./routes/admin/PropRouter');  //prop
const WorkRouter = require('./routes/admin/WorkRouter');  //work
const RateRouter = require('./routes/admin/RateRouter');  //rate
//web的
const webNewsRouter = require('./routes/web/NewsRouter');  //news
const webWorkRouter = require('./routes/web/WorkRouter');  //news
const webUserRouter = require('./routes/web/UserRouter');  
const webRouter = require('./routes/web/RateRouter');  //rate


const JWT = require('./util/JWT');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

//web
app.use(webNewsRouter)
app.use(webWorkRouter)
app.use(webUserRouter)
app.use(webRouter)


// app.use('/props', usersRouter);
// /adminapi/*  后台系统用的
// /webapi/*  企业官网用的
app.use((req,res,next)=>{
  // 如果token有效，next（）
  //如果token过期了，返回401错误
  if(req.url==="/adminapi/user/login"){
    next()
    return;
  }
  const token = req.headers["authorization"].split(" ")[1]
  if(token){
    var payload = JWT.verify(token)
    console.log(payload)
    if(payload){
      const newToken = JWT.generate({
        _id:payload._id,
        username:payload.username
      },"1d")// 设置时长 controller里面有 "10s"   1d = 1 天
      res.header("Authorization",newToken)
      next()
    }else{
      res.status(401).send({errCode:"-1",errorInfo:"token过期"})
    }
  }
  
})
app.use(UserRouter)
app.use(PropRouter)
app.use(NewsRouter)
app.use(WorkRouter)
app.use(RateRouter)



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



module.exports = app;
